// jsonp网络请求
const jsonp = function(url, data) {
	return new Promise((resolve, reject) => {
		// 1.初始化url
		let dataString = url.indexOf('?') === -1 ? '?' : '&'
		let callbackName = `jsonpCB_${ Date.now() }`;
		url += `${ dataString }callback=${ callbackName }`
		if (data) {
			// 2.有请求参数，依次添加到url
			for (let k in data) {
				url += `&${ k }=${ data[k] }`
			}
		}
		let scriptNode = document.createElement('script');
		scriptNode.src = url;
		// 3. callback
		window[callbackName] = (result) => {
			result ? resolve(result) : reject('没有返回数据');
			delete window[callbackName];
			document.body.removeChild(scriptNode);
		}
		// 4. 异常情况
		scriptNode.addEventListener('error', () => {
			reject('接口返回数据失败');
			delete window[callbackName];
			document.body.removeChild(scriptNode);
		}, false)
		// 5. 开始请求
		document.body.appendChild(scriptNode)
	})
}
//格式化时间  type=1反日/2反月日/3反年月日,4XXXX-XX-XX
const date = function(date = new Date(), type = 4) {
	var year = date.getFullYear();
	var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
	var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
	var str;
	switch (type) {
		case 1:
			str = day + '日';
			break;
		case 2:
			str = month + '月' + day + '日';
			break;
		case 3:
			str = year + '年' + month + '月' + day + '日';
			break;
		case 4:
			str = year + '-' + month + '-' + day;
			break;
	}
	return str;
}
// ASCII码排序
const ASCII = function(obj) {
	let arr = new Array();
	let num = 0;
	for (let i in obj) {
		arr[num] = i;
		num++;
	}
	let sortArr = arr.sort();
	//let sortObj = {};    //完成排序值
	let str = ''; //自定义排序字符串
	for (let i in sortArr) {
		str += sortArr[i] + '=' + obj[sortArr[i]] + '&';
		//sortObj[sortArr[i]] = obj[sortArr[i]];
	}
	//去除两侧字符串
	let char = '&'
	str = str.replace(new RegExp('^\\' + char + '+|\\' + char + '+$', 'g'), '');

	return str;
}
//禁止多次点击
var PageActive = true;
const preventActive = function(fn) {
	if (PageActive) {
		PageActive = false
		if (fn) fn()
		setTimeout(() => {
			PageActive = true
		}, 1500); //设置该时间内重复触发只执行第一次，单位ms，按实际设置
	} else {
		console.log('重复点击或触发')
	}
}


export default {
	jsonp,
	ASCII,
	date,
	preventActive,
}
